package org.sundatagroup.aurora.core.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.sundatagroup.aurora.core.entity.model.ModuleModel;
import org.sundatagroup.aurora.core.entity.pojo.Module;

import java.util.List;

/**
 * <p>{@link Module} 类的相关 DAO 操作, 使用的是 {@link ModuleModel} 类
 * </p>
 * 
 * @version 0.1.1
 * 
 * @author Zdream
 * @author CharlesChen
 * @date 2018-04-03
 * @since 0.1
 */
@Repository
public class ModuleDao {
    @Autowired
    MongoTemplate mongoOps;

    private final static Logger LOGGER = LoggerFactory.getLogger(ModuleDao.class);
    /**
     * 增操作：增加一个{@link ModuleModel}
     */
    public void add(ModuleModel m) {
        mongoOps.insert(m);
    }
    
    /**
     * 查操作：查找一个{@link ModuleModel}
     * @param mid
     * @return
     */
    public ModuleModel findByMid(int mid) {
        ModuleModel mm;
        Query query = Query.query(Criteria.where("mid").is(mid));
        if ((mm = mongoOps.findOne(query, ModuleModel.class)) == null) {
            LOGGER.error("利用mid查询Module失败，请检查！");
            return null;
        } else {
            return mm;
        }
    }
    
    /**
     * 查操作：查询List<mid>的所有{@link ModuleModel}
     * @param mids mid集合
     * @return
     */
    public List<ModuleModel> findAll(List<Integer> mids) {
    	Criteria criatira = new Criteria();
    	
    	mids.forEach((mid) -> {
    		criatira.orOperator(Criteria.where("mid").is(mid));
    	});
    	
        return mongoOps.find(new Query(criatira), ModuleModel.class);
    }

    /**
     * 返回所有的 {@link Module}
     * @return
     */
    public List<ModuleModel> findAll() {
        List<ModuleModel> mms;
        if ((mms = mongoOps.findAll(ModuleModel.class)) == null) {
            LOGGER.error("查询所有的Module结果为null，请检查");
            return null;
        } else {
            return mms;
        }
    }

    /**
     * 用分页的方式进行{@link ModuleModel}的查询
     * @param start 起始索引
     * @param size 数据条目
     * @return
     */
    public List<ModuleModel> findByPage(int start, int size) {
        List<ModuleModel> mms;
        Query query = new Query()
                .with(new Sort(new Sort.Order(Sort.Direction.ASC, "mid")))
                .skip(start)
                .limit(size);
        if ((mms = mongoOps.find(query, ModuleModel.class)) == null) {
            LOGGER.error("分页查询Module为null，请检查！");
            return null;
        } else {
            return mms;
        }
    }

    /**
     * 返回 {@link Module} 数量
     * @return
     */
    public int count() {
    	return (int) mongoOps.count(new Query(), ModuleModel.class);
    }
}
